package com.cn.aam.checaiduo.ui.me;

import android.content.Intent;
import android.graphics.Bitmap;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.cn.aam.checaiduo.AppData;
import com.cn.aam.checaiduo.Const;
import com.cn.aam.checaiduo.R;
import com.cn.aam.checaiduo.backend.RetrofitHome;
import com.cn.aam.checaiduo.backend.observer.OnRequestListener;
import com.cn.aam.checaiduo.backend.rx.RxSchedulers;
import com.cn.aam.checaiduo.base.BaseActivity;
import com.cn.aam.checaiduo.base.ToolBarManager;
import com.cn.aam.checaiduo.bean.base.NormalResponseB;
import com.cn.aam.checaiduo.bean.me.InviteB;
import com.cn.aam.checaiduo.ui.arouter.UIRouter;
import com.cn.aam.checaiduo.ui.me.adapter.InviteAdapter;
import com.cn.aam.checaiduo.utils.QRCordeUtils;
import com.cn.aam.checaiduo.utils.WindowsUtils;
import com.cn.aam.checaiduo.widget.WMToast;
import com.orhanobut.logger.Logger;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * monker on 2017/5/25.
 * 邀请有奖
 */
@Route(path = UIRouter.ME.AC_INVITEPRIZES)
public class InvitePrizesActivity extends BaseActivity {

    @BindView(R.id.invite_iv_qcImg)
    ImageView inviteIvQcImg;
    @BindView(R.id.invite_tv_shareCode)
    TextView inviteTvShareCode;
    @BindView(R.id.invite_tv_cashAmount)
    TextView inviteTvCashAmount;
    @BindView(R.id.invite_tv_personNum)
    TextView inviteTvPersonNum;
    @BindView(R.id.invite_recycler)
    RecyclerView inviteRecycler;

    private String shareUrl;
    private boolean isInviting = false;//是否点击了邀请，防止多次点击邀请弹出多个微信界面

    @Override
    protected int layoutId() {
        return R.layout.activity_invite_prizes;
    }

    @Override
    protected void initView() {
        super.initView();
        ToolBarManager.with(this, WMContent).setNavigationIcon(R.drawable.ic_nav_arrow_white)
                .setTitle("邀请有奖");
        getInfo();
    }

    /**
     * 时间：2017/6/29
     * 描述：显示二维码
     */
    private void createImg(final String url) {

//        final StringBuilder builder = new StringBuilder("http://pan.baidu.com/share/qrcode?w=150&h=150&url=");
//        builder.append(url);
//        Glide.with(mContext).load(builder.toString()).centerCrop().into(inviteIvQcImg);

        Observable.create(new ObservableOnSubscribe<Bitmap>() {
            @Override
            public void subscribe(ObservableEmitter<Bitmap> e) throws Exception {
//                Bitmap bmp = QRCodeEncoder.syncEncodeQRCode(url, 150, Color.BLACK);
                Bitmap bmp = QRCordeUtils.createQRImage(mContext, url, null);
                e.onNext(bmp);
                e.onComplete();
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Bitmap>() {
                    @Override
                    public void accept(Bitmap bitmap) throws Exception {
                        inviteIvQcImg.setVisibility(View.VISIBLE);
                        inviteIvQcImg.setImageBitmap(bitmap);
                    }
                });
    }

    /**
     * 时间：2017/6/28
     * 描述：加载邀请信息
     */
    private void getInfo() {
//        final StringBuilder builder = new StringBuilder("http://pan.baidu.com/share/qrcode?w=150&h=150&url=");
        RetrofitHome.getInstance()
                .getInternalApi()
                .inviteInfo(AppData.getToken())
                .compose(RxSchedulers.<NormalResponseB<InviteB>>toMain())
                .subscribe(new OnRequestListener<NormalResponseB<InviteB>>(this) {
                    @Override
                    public void onNext(NormalResponseB<InviteB> value) {
                        super.onNext(value);
                        if (value.getIsLogged() != Const.STATE_LOGIN) {
                            goLogin();
                            return;
                        }


                        String shareCode = value.getData().getShare_code();
                        String crashAmount = value.getData().getCash_amount();
                        String num = value.getData().getInvite_number();
                        if (crashAmount == null) {
                            crashAmount = "0";
                        } else {
                            if (crashAmount.contains(".")) {
                                crashAmount = crashAmount.substring(0, crashAmount.indexOf("."));
                            }
                        }

                        inviteTvShareCode.setText(shareCode);
                        inviteTvCashAmount.setText(crashAmount + "元");
                        inviteTvPersonNum.setText(num + "人");
                        shareUrl = value.getData().getShare_url();

                        createImg(shareUrl);
                        setRecycler(value.getData().getInvite_list());
                    }
                });
    }

    private void setRecycler(List<InviteB.InviteListBean> list) {
        InviteAdapter adapter = new InviteAdapter(mContext);
        adapter.setDataList(list);
        inviteRecycler.setLayoutManager(new LinearLayoutManager(mContext));
        inviteRecycler.setAdapter(adapter);
        if (list.size() > 10) {
            //如果被邀请人的数量大于10个，那么显示10条数据
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT
                    , WindowsUtils.dip2px(460));
            inviteRecycler.setLayoutParams(params);
        }

    }

    @OnClick(R.id.tv_inviteNow)
    void clickToInvite() {
        if (isInviting) return;//已经点击了邀请，还没有回调
        UMImage image = new UMImage(this, R.mipmap.ic_launcher);
        UMWeb web = new UMWeb(shareUrl);
        web.setTitle("好友邀请");//标题
        web.setThumb(image);  //缩略图
        web.setDescription("您的好友邀请您加入悟空车金融理财，赶紧点击查看吧！");//描述
//        CustomDialogCenter.getInstance().showShareDialog(this, web);
        new ShareAction(this).setPlatform(SHARE_MEDIA.WEIXIN)
                .withMedia(web)
                .setCallback(umShareListener)
                .share();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);

    }

    private UMShareListener umShareListener = new UMShareListener() {
        @Override
        public void onStart(SHARE_MEDIA platform) {
            isInviting = true;
            //分享开始的回调
        }

        @Override
        public void onResult(SHARE_MEDIA platform) {
            isInviting = false;
            WMToast.normal("邀请成功");
        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            isInviting = false;
            if (t.toString().contains("没有安装应用"))
                WMToast.normal("未安装微信应用");
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
            isInviting = false;
            Logger.d("取消邀请");
        }
    };
}
